/**
 * 动作处理器
 * 处理文件操作、搜索替换、字体大小调整等功能
 */
export class ActionHandlers {
    constructor(editor, options = {}) {
        this.editor = editor
        this.options = {
            fontSizeStep: 2,
            minFontSize: 10,
            maxFontSize: 30,
            ...options
        }
    }

    /**
     * 处理保存操作
     */
    handleSave() {
        try {
            const content = this.editor.editor.value
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
            const url = URL.createObjectURL(blob)

            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = url
            a.download = this.editor.title || 'code.txt'
            document.body.appendChild(a)
            a.click()

            URL.revokeObjectURL(url)
            document.body.removeChild(a)

            this.emit('keybinding:save', { filename: this.editor.title, content })
            return true
        } catch (error) {
            logger.error('保存文件时出错:', error)
            this.emit('keybinding:error', { action: 'save', error })
            return false
        }
    }

    /**
     * 新建文件
     */
    handleNewFile() {
        if (confirm('确定要新建文件吗？当前内容将会清空。')) {
            this.editor.editor.value = ''
            this.editor._updateEditor()
            this.emit('keybinding:newFile')
            return true
        }
        return false
    }

    /**
     * 打开文件
     */
    handleOpenFile() {
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = '.txt,.js,.html,.css,.json,.md'
        input.onchange = (e) => {
            const file = e.target.files[0]
            if (file) {
                const reader = new FileReader()
                reader.onload = (e) => {
                    this.editor.editor.value = e.target.result
                    this.editor._updateEditor()
                    this.emit('keybinding:openFile', { filename: file.name, content: e.target.result })
                }
                reader.readAsText(file)
            }
        }
        input.click()
    }

    /**
     * 处理撤销操作
     */
    handleUndo() {
        if (this.editor.undo && typeof this.editor.undo === 'function') {
            this.editor.undo()
            this.emit('keybinding:undo')
            return true
        }
        return false
    }

    /**
     * 处理重做操作
     */
    handleRedo() {
        if (this.editor.redo && typeof this.editor.redo === 'function') {
            this.editor.redo()
            this.emit('keybinding:redo')
            return true
        }
        return false
    }

    /**
     * 处理查找操作
     */
    handleFind() {
        // 发射事件，由其他插件实现查找功能
        this.emit('keybinding:find')
    }

    /**
     * 处理替换操作
     */
    handleReplace() {
        // 发射事件，由其他插件实现替换功能
        this.emit('keybinding:replace')
    }

    /**
     * 找下一个
     */
    handleFindNext() {
        this.emit('keybinding:findNext')
    }

    /**
     * 找上一个
     */
    handleFindPrevious() {
        this.emit('keybinding:findPrevious')
    }

    /**
     * 跳转到指定行
     */
    handleGoToLine() {
        const lineNumber = prompt('跳转到行号:')
        if (lineNumber && !isNaN(lineNumber)) {
            const lines = this.editor.editor.value.split('\n')
            const targetLine = Math.max(1, Math.min(parseInt(lineNumber), lines.length))

            // 计算位置
            let position = 0
            for (let i = 0; i < targetLine - 1; i++) {
                position += lines[i].length + 1
            }

            this.editor.editor.selectionStart = this.editor.editor.selectionEnd = position
            this.editor.editor.focus()

            this.emit('keybinding:goToLine', { lineNumber: targetLine })
            return true
        }
        return false
    }

    /**
     * 剪切
     */
    handleCut() {
        if (this.editor.editor.selectionStart !== this.editor.editor.selectionEnd) {
            document.execCommand('cut')
            this.editor._updateEditor()
            this.emit('keybinding:cut')
            return true
        }
        return false
    }

    /**
     * 复制
     */
    handleCopy() {
        if (this.editor.editor.selectionStart !== this.editor.editor.selectionEnd) {
            document.execCommand('copy')
            this.emit('keybinding:copy')
            return true
        }
        return false
    }

    /**
     * 粘贴
     */
    async handlePaste() {
        try {
            // 使用现代剪贴板 API
            if (navigator.clipboard && navigator.clipboard.readText) {
                const text = await navigator.clipboard.readText()
                this.insertTextAtCursor(text)
            } else {
                // 退化到传统方法（但这可能不工作，因为已经 preventDefault 了）
                logger.warn('剪贴板 API 不可用，请使用 Ctrl+V 直接粘贴')
                // 不阻止默认行为，让浏览器处理粘贴
                return false
            }
            
            this.editor._updateEditor()
            this.emit('keybinding:paste')
            return true
        } catch (error) {
            logger.error('粘贴失败:', error)
            // 如果粘贴失败，返回 false 让浏览器处理
            return false
        }
    }

    /**
     * 在光标位置插入文本
     * @param {string} text - 要插入的文本
     */
    insertTextAtCursor(text) {
        const editor = this.editor.editor
        const start = editor.selectionStart
        const end = editor.selectionEnd
        const value = editor.value
        
        // 插入文本
        const newValue = value.substring(0, start) + text + value.substring(end)
        editor.value = newValue
        
        // 设置新的光标位置
        const newCursorPos = start + text.length
        editor.selectionStart = editor.selectionEnd = newCursorPos
        
        // 聚焦编辑器
        editor.focus()
    }

    /**
     * 处理运行代码操作
     */
    handleRunCode() {
        const code = this.editor.editor.value
        this.emit('keybinding:runCode', { code })
    }

    /**
     * 改变编辑器字体大小
     * @param {string} direction - 方向：'+' 增大，'-' 减小
     */
    changeFontSize(direction) {
        const computedStyle = window.getComputedStyle(this.editor.editor)
        let fontSizeNumber = parseInt(computedStyle.fontSize)

        if (direction === '+') {
            fontSizeNumber = Math.min(fontSizeNumber + this.options.fontSizeStep, this.options.maxFontSize)
        } else if (direction === '-') {
            fontSizeNumber = Math.max(fontSizeNumber - this.options.fontSizeStep, this.options.minFontSize)
        }

        // 应用新的字体大小
        const newFontSize = `${fontSizeNumber}px`
        this.editor.editor.style.fontSize = newFontSize
        this.editor.lineNumbers.style.fontSize = newFontSize

        // 如果有高亮层，也更新字体大小
        if (this.editor.highlightLayer) {
            this.editor.highlightLayer.style.fontSize = newFontSize
        }

        this.editor._updateEditor()
        this.emit('keybinding:fontSizeChanged', { fontSize: fontSizeNumber })
        return fontSizeNumber
    }

    /**
     * 重置字体大小
     */
    resetFontSize() {
        const defaultFontSize = '14px'
        this.editor.editor.style.fontSize = defaultFontSize
        this.editor.lineNumbers.style.fontSize = defaultFontSize

        if (this.editor.highlightLayer) {
            this.editor.highlightLayer.style.fontSize = defaultFontSize
        }

        this.editor._updateEditor()
        this.emit('keybinding:resetFontSize', { fontSize: 14 })
        return 14
    }

    /**
     * 切换全屏
     */
    handleToggleFullscreen() {
        if (document.fullscreenElement) {
            document.exitFullscreen()
        } else {
            document.documentElement.requestFullscreen()
        }
        this.emit('keybinding:toggleFullscreen')
    }

    /**
     * 处理Escape键
     */
    handleEscape() {
        // 取消选中或其他操作
        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = this.editor.editor.selectionStart
        this.emit('keybinding:escape')
    }

    /**
     * 跳转到匹配的括号
     */
    handleJumpToBracket() {
        // 简化实现，只发射事件
        this.emit('keybinding:jumpToBracket')
    }

    /**
     * 选中所有相同内容（简化实现）
     */
    handleSelectAllOccurrences() {
        // 这里只是发射事件，实际实现可能需要更复杂的逻辑
        this.emit('keybinding:selectAllOccurrences')
    }

    /**
     * 发射事件的便捷方法
     * @param {string} event - 事件名
     * @param {*} data - 事件数据
     */
    emit(event, data) {
        if (this.editor && this.editor.emit) {
            this.editor.emit(event, data)
        }
    }

    /**
     * 更新配置
     * @param {Object} newOptions - 新的配置选项
     */
    updateOptions(newOptions) {
        this.options = { ...this.options, ...newOptions }
    }
}